var crypto = require('crypto');
var eventproxy = require('eventproxy');

var mongoose = require('./db.js');


var userSchema = mongoose.Schema({
	name: String,
	pwd: String,
	email: String,
	age: Number,
	avatar: String
});

var User = mongoose.model('User', userSchema);

var userDAO = function(){};

userDAO.prototype.regist = function (user, callback) {
	var errors = [];
    var ep = new eventproxy();

    ep.all('checkName', 'checkEmail', function () {
        if(errors.length > 0){
            callback(null, errors);
        } else {
            var md5 = crypto.createHash('md5');
            user.pwd = md5.update(user.pwd).digest('hex');
            user.age = 0; //初始化年龄为0
            user.avatar = "imgs/avatars/default.png"; //头像路径

            var u = new User(user);
            u.save(function (e){
                callback(user, e);
            });
        }
    });

	User.findOne({name: user.name}, function (e, userExist) {
		if (userExist) {
			errors.push('用户名已存在！');
		}
        ep.emit('checkName');
	});

	User.findOne({email: user.email}, function(e, userExist){
		if(userExist){
			errors.push( '邮箱已被注册！');
		}
        ep.emit('checkEmail')
	});


};

userDAO.prototype.login = function (user, callback) {

	var md5 = crypto.createHash('md5');
	user.pwd = md5.update(user.pwd).digest('hex');
	
	User.findOne({email: user.email, pwd: user.pwd}, function (e, obj) {
		callback(obj, e);
	});

};

userDAO.prototype.findByNameAndPwd = function (userName, pwd, callback) {
	var md5 = crypto.createHash('md5');
	pwd = md5.update(pwd).digest('hex');

	User.findOne({name: userName, pwd: pwd}, callback);
}

userDAO.prototype.findUserByName = function (userName, callback){
	
	User.findOne({name: userName}, callback);
	
};
/**
 * Model.update({conditions: }, {updateDocs: }, {options: }, callback(err, numberAffected, raw));
 */
userDAO.prototype.updateName = function (name, newName, callback) {
    User.update({name: name}, {$set: {name: newName}},{}, callback );
}

userDAO.prototype.updateEmail = function (userName, email, callback) {
	User.findOne({email: email}, function (e, userExist) {
        if(userExist){
            callback('邮箱已被注册！');
        } else {
            User.update({name: userName}, {$set: { email: email }}, {}, callback);
        }
    });

};

userDAO.prototype.updateAvatar = function (userName, path, callback) {
	User.update({name: userName}, {$set: { avatar: path }}, {}, callback);
};

userDAO.prototype.updatePwd = function (userName, pwd, callback) {
	var md5 = crypto.createHash('md5');
	var pwd = md5.update(pwd).digest('hex');
	User.update({name: userName}, {$set: { pwd: pwd }}, {}, callback);
};

userDAO.prototype.searchUser = function (key, callback) {
    var query = {name: new RegExp(key)};
    User.find(query, callback);
};
/**
 * @param start 开始查找的index
 * @param n 查找个数
 */
userDAO.prototype.getUserByPage = function(start, n, callback){
    User.find().skip(start).limit(n).lean().exec(callback);
};

userDAO.prototype.getUsersCount = function(callback){
    User.count(callback);
};

userDAO.prototype.findUserById = function(id, callback){
    User.find({_id: id}, callback);
}

userDAO.prototype.deleteUserById = function(id, callback){
      User.remove({_id: id}, callback);
};

module.exports = new userDAO();